package com.example.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.blog.dao.mapper.TagsMapper;
import com.example.blog.dao.pojo.Tag;
import com.example.blog.service.TagsService;
import com.example.blog.vo.Result;
import com.example.blog.vo.TagVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class TagsServiceImpl implements TagsService {

    @Autowired
    private TagsMapper tagsMapper;

    @Override
    public List<TagVo> findTagsByArticleId(long articleId) {
        List<Tag> tagsByArticleId = tagsMapper.findTagsByArticleId(articleId);
        return copyList(tagsByArticleId);
    }

    @Override
    public List<TagVo> findHotTags(int limit) {
        List<Long> hotTagIds = tagsMapper.findHotTagId(limit);
        if (CollectionUtils.isEmpty(hotTagIds)) {
            return Collections.emptyList();
        }
        List<Tag> tagList = tagsMapper.findTagsInIds(hotTagIds);
        return copyList(tagList);
    }

    @Override
    public Result findAllTags() {
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Tag::getId, Tag::getTagName);
        List<Tag> tagList = tagsMapper.selectList(queryWrapper);
        return Result.success(copyList(tagList));

    }

    @Override
    public Result findAllTagsDetail() {
        List<Tag> tagList = tagsMapper.selectList(null);
        return Result.success(copyList(tagList));
    }

    @Override
    public Result findTagsDetailById(Long tagId) {
        Tag tag = tagsMapper.selectById(tagId);
        return Result.success(copy(tag));
    }

    private List<TagVo> copyList(List<Tag> tagsList) {
        List<TagVo> tagVoList = new ArrayList<>();
        for (Tag tag : tagsList) {
            tagVoList.add(copy(tag));
        }
        return tagVoList;
    }

    private TagVo copy(Tag tag) {
        TagVo tagVo = new TagVo();
        tagVo.setId(String.valueOf(tag.getId()));
        BeanUtils.copyProperties(tag, tagVo);
        return tagVo;
    }
}
